package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Batch;
import com.briup.pts.domain.bean.QuarantineRegistration;
import com.briup.pts.mapper.BatchMapper;
import com.briup.pts.mapper.QuarantineRegistrationMapper;
import com.briup.pts.service.QuarantineRegistrationService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class QuarantineRegistrationServiceImpl implements QuarantineRegistrationService {

    private final QuarantineRegistrationMapper qrMapper;
    private final BatchMapper batchMapper;

    @Override
    public PageInfo<QuarantineRegistration> pageQueryByConditional(
            Integer pageNum, Integer pageSize, String bQualified, String grMechanism) {
        // 开始分页，通过PageHelper实现分页；注意PageHelper使用后需要关闭资源
        try (Page<QuarantineRegistration> ignored = PageHelper.startPage(pageNum, pageSize)) {
            // 根据条件查询数据
            List<QuarantineRegistration> list = qrMapper.queryByConditional(bQualified, grMechanism);
            // 将数据转换为PageInfo数据，需要先将集合转换为Page类型后，放入到PageInfo中
            Page<QuarantineRegistration> page = (Page<QuarantineRegistration>) list;
            return new PageInfo<>(page);
        }
    }

    @Override
    public void saveOrUpdate(QuarantineRegistration qr) {
        // 检验传入的批次是否存在
        String batchId = qr.getGrBatchId();
        Batch batch = batchMapper.queryById(batchId);
        if (batch == null) {
            throw new ServiceException(ResultCode.BATCH_IS_NOT_EXISTS);
        }

        // 根据是否传入id决定是新增还是修改检疫报告
        if (qr.getGrId() != null) {
            // 表示修改，当前不支持修改质检报告的内容
            throw new ServiceException(ResultCode.QUALIFIED_MODIFIED_IS_NOT_SUPPORT);
        } else {
            // 如果id为空表示，新增
            qrMapper.addQr(qr);
        }

        //修改对应批次中的检疫状态
        batch.setBQuarantine("已检疫");
        batch.setBQualified(qr.getBQualified());
        batchMapper.updateBatchInfo(batch);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        qrMapper.deleteBatch(ids);
    }
}